package org.example.BinaryTree;

import java.util.ArrayList;
import java.util.List;

public class The_layer_average_of_a_binary_tree {
    public static ArrayList<List<Double>> arrayList = new ArrayList<>();
    public static void main(String[] args) {
        //二叉树的层平均值

        //给定一个非空二叉树的根节点 root , 以数组的形式返回每一层节点的平均值。与实际答案相差 10-5 以内的答案可以被接受。
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode root = new TreeNode(0);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);
        root.left = node1;
        root.right = node2;
        node1.left = node3;
        node1.right = node4;
        node2.left = node5;
        node2.right = node6;
        node5.left = node7;
        get(root,0);
        ArrayList<Double> list = new ArrayList<>();
        for (int i = 0; i < arrayList.size(); i++) {
            int size = arrayList.get(i).size();
            double num = 0;
            for (Double j : arrayList.get(i)) {
                num += j;
            }
            list.add(num/size);
        }
        for (Double i : list) {
            System.out.print(i+" ");
        }
    }
    public static void get(TreeNode root,int deep) {
        if (root==null) return;
        deep++;
        if (arrayList.size()<deep){
            ArrayList<Double> item = new ArrayList<>();
            arrayList.add(item);
        }
        arrayList.get(deep-1).add((double) root.val);
        get(root.left,deep);
        get(root.right,deep);
    }
}
